package com.zxt.web.controller;

import com.zxt.domain.Goods;
import com.zxt.domain.PageBean;
import com.zxt.service.GoodsService;
import com.zxt.service.impl.GoodsServiceImpl;
import com.zxt.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * projectName:myXiaoMi
 * author:ZhangXiaoTeng
 * time:2021/12/6 13:14
 * description:
 */
@WebServlet("/goodsservlet")
@MultipartConfig(maxFileSize = 5*1024*1024,maxRequestSize = 1024*1024*20)
public class GoodsServlet extends BaseServlet {
    /**
     * 分页查询
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String getGoodsListByTypeId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取前端数据
        //获取页面
        String pageNum = request.getParameter("pageNum");
        //页大小
        String pageSize = request.getParameter("pageSize");
        //商品类别
        String typeId = request.getParameter("typeId");
        //商品名称
        String goodsName = request.getParameter("goodsName");
        //校验数据
        int page_num = 1;
        int page_size = 8;
        try {
            if (!StringUtils.isEmpty(pageNum)) {
                page_num = Integer.parseInt(pageNum);
                if (page_num < 0) {
                    page_num = 1;
                }
            }
            if (!StringUtils.isEmpty(pageSize)) {
                page_size = Integer.parseInt(pageSize);
                if (page_size < 0) {
                    page_size = 8;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //封装条件
        StringBuilder where = new StringBuilder(" where 1=1 ");
        List<Object> params = new ArrayList<Object>();
        if (!StringUtils.isEmpty(typeId)) {
            where.append(" and typeid=? ");
            params.add(typeId);
        }
        if (!StringUtils.isEmpty(goodsName)) {
            where.append(" and name like ? ");
            params.add("%" + goodsName + "%");
        }
        //没有商品
        if (params.size() <= 0) {
            return "/goodsList.jsp";
        }
        //2调用业务逻辑
        GoodsService goodsService = new GoodsServiceImpl();
        try {
            PageBean<Goods> pageBean = goodsService.findByPage(page_num, page_size, where.toString(), params);
            request.setAttribute("pageBean", pageBean);
            request.setAttribute("typeId", typeId);
            request.setAttribute("goodsName", goodsName);
            //3转发重定向
            return "/goodsList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:index.jsp";
    }

    //根据商品id查询商品
    public String getGoodsById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String id = request.getParameter("id");
        //判断
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "商品id不能为空");
            return "/message.jsp";
        }
        try {
            //2.调用业务逻辑
            GoodsService goodsService = (GoodsService) new GoodsServiceImpl();
            Goods goods = goodsService.findById(Integer.parseInt(id));
            request.setAttribute("goods", goods);
            //3.转发重定向
            return "/goodsDetail.jsp";
        } catch (Exception e) {
            request.setAttribute("msg", "商品查询失败" + e.getMessage());
            return "/message.jsp";
        }
    }


    //后台添加商品
    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //1.判断是否登录
        //2.获取前端数据
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        //图片
        Part picture = request.getPart("picture");

        //校验
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "商品名称不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(typeid)) {
            request.setAttribute("msg", "商品类别不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(pubdate)) {
            request.setAttribute("msg", "上架时间不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(price)) {
            request.setAttribute("msg", "商品价格不能为空");
            return "/admin/addGoods.jsp";
        }
        if (StringUtils.isEmpty(star)) {
            request.setAttribute("msg", "商品热销指数不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(intro)) {
            request.setAttribute("msg", "商品介绍不能为空");
            return "/admin/addGoods.jsp";
        }
        try {
            int type_id = Integer.parseInt(typeid);
            if (type_id <= 0) {
                request.setAttribute("msg", "请选择合适类型");
                return "/admin/addGoods.jsp";
            }
            //4处理图片
            //4.1保存图片
            //处理IE路径
            String dis = picture.getHeader("Content-Disposition");
            String filename = dis.substring(dis.lastIndexOf("filename") + 10, dis.length() - 1);
            filename=filename.substring(filename.lastIndexOf("\\")+1);//101.jpg
            String uuidfilename=null;
            if (!filename.equals("")) {
                //保存图片
                //生成图片目录
                String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "images");
                File dir=new File(basePath);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                //获取后缀名
                String ext = filename.substring(filename.lastIndexOf(".") + 1);//jpg
                uuidfilename= UUID.randomUUID().toString().replace("-","");
                uuidfilename=uuidfilename+"."+ext;//45345356.jpg
                picture.write(basePath+File.separator+uuidfilename);
                picture.delete();
                System.out.println("图片保存成功");
            }
            //添加到数据库
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Goods goods=new Goods(0,name,sdf.parse(pubdate),uuidfilename,new BigDecimal(price),Integer.parseInt(star),intro,Integer.parseInt(typeid));
            GoodsService goodsService=new GoodsServiceImpl();
            goodsService.add(goods);
            //5转发重定向
            response.getWriter().write("<script>alert('添加成功');window.location='admin/addGoods.jsp'</script>");
        } catch (Exception e) {
            response.getWriter().write("<script>alert('添加失败');window.location='admin/addGoods.jsp'</script>");

        }
        return null;

    }

}
